import base64
import pickle
from random import randint

# Create your views here.
from django.core.serializers import get_serializer
from django_redis import get_redis_connection
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from celery_tasks.sms.tasks import send_sms_code
from goods.models import SKU
from goods.serializers import GoodsSerializer
from users.models import User
from users.serializers import UserSerializer, UserDetailSerializer, EmailSerializer, VerifyEmailSerializer, \
    AddUserBrowsingHistorySerializer


class SMSCodeView(APIView):
    def get(self, request, mobile):
        # 控制短信频率
        conn = get_redis_connection("verify_codes")
        flag = conn.get("sms_flag_{}".format(mobile))
        if flag:
            return Response({"error": "请求过于频繁"}, status=402)

        # 生成短信验证码
        sms_code = '%06d' % randint(0, 999999)

        # send_sms_code.delay(mobile, sms_code, 5)
        # result = send_sms_code.delay(mobile, sms_code, 5)
        print(sms_code)
        # 保存手机号和验证码到redis中
        # if result == 0:
        p1 = conn.pipeline()
        p1.set("sms_{}".format(mobile), sms_code, ex=300)
        p1.set('sms_flag_{}'.format(mobile), 1, ex=60)
        p1.execute()

        return Response({"message": "OK"})


class MobileCountView(APIView):
    def get(self, request, mobile):
        # 查询手机号是否存在
        count = User.objects.filter(mobile=mobile).count()
        return Response({"count": count})


class UserNameCountView(APIView):

    def get(self, reqeust, username):
        # 查询数据对象数量
        count = User.objects.filter(username=username).count()

        return Response({'count': count})


class UserView(CreateAPIView):
    serializer_class = UserSerializer


class UserDetailView(RetrieveAPIView):
    serializer_class = UserDetailSerializer
    queryset = User.objects.all()

    # 重写get_object方法
    def get_object(self):
        return self.request.user


class UserEmailView(UpdateAPIView):
    serializer_class = EmailSerializer

    # 重写get_object方法，自定义返回
    def get_object(self):
        return self.request.user


class VerifyEmail(GenericAPIView):
    serializer_class = VerifyEmailSerializer

    def get(self, request):
        """因为createAPIView的ｄａｔａ获取不是我们想要的，所以重写自定义get方法"""
        # 获取token 数据
        data = request.query_params

        # 验证数据并更新
        ser = self.get_serializer(data=data)
        ser.is_valid()
        ser.save()

        # 返回结果
        return Response({"message": 'ok'})


class UserBrowsingHistoryView(CreateAPIView, ListAPIView):
    # serializer_class = AddUserBrowsingHistorySerializer
    def get_serializer_class(self):
        # 判断请求方式调用不同序列化器
        if self.request.method == "post":
            return AddUserBrowsingHistorySerializer
        else:
            return GoodsSerializer

    def get_queryset(self):
        # 连接redis缓存
        conn = get_redis_connection('history')
        user = self.request.user
        # 获取列表
        sku_ids = conn.lrange("history_{}".format(user.id), 0, 5)
        return SKU.objects.filter(id__in=sku_ids)


class UserLoginView(ObtainJSONWebToken):
    """重写登录"""

    def post(self, request, *args, **kwargs):
        # 调用父类方法，重写登录验证
        response = super().post(request, *args, **kwargs)

        # 重写序列化器
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            user = serializer.object.get("user") or request.user
            response = merge_cart_cookie_to_redis(request, response, user)
            return response

        return response
